<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="KouriChat - 配置中心">
    <meta name="keywords" content="AI,KouriChat">
    <meta name="theme-color" content="#6366f1">
    <title>KouriChat - 配置中心</title>
    <link href="/static/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdmirror.com/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css" rel="stylesheet">
    <link rel="icon" type="image/x-icon" href="/static/mom.ico">
    <style>
        :root {
            --primary-color: #6366f1;
            --secondary-color: #4f46e5;
            --background-color: #f0f4f8;  /* 更柔和的浅蓝灰色背景 */
            --text-color: #1e293b;
            --card-bg: rgba(255, 255, 255, 0.494);
            --card-border: rgba(255, 255, 255, 0.5);
            --card-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
        }

        [data-bs-theme="dark"] {
            --background-color: #1a1f2e;  /* 更柔和的深色背景 */
            --text-color: #f8fafc;
            --card-bg: rgba(30, 41, 59, 0.612);
            --card-border: rgba(255, 255, 255, 0.1);
            --card-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.2), 0 2px 4px -1px rgba(0, 0, 0, 0.1);
        }
        html,body{
            height:100%;
            margin: 0;
        }
        body {
            background: var(--background-color);
            color: var(--text-color);
            transition: all 0.3s ease;
            background-repeat: no-repeat;
            background-size: cover;
            background-position: center;
            background-attachment: fixed;
            min-height: 100vh;
        }

        .config-section {
            background: var(--card-bg);
            -webkit-backdrop-filter: blur(5px);
            backdrop-filter: blur(5px);
            border-radius: 1rem;
            border: 1px solid var(--card-border);
            box-shadow: var(--card-shadow);
            padding: 2rem;
            margin-bottom: 2rem;
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
            opacity: 0;
            transform: translateY(20px);
            animation: slideUp 0.5s ease forwards;
            animation-delay: 0.1s;
        }

        @keyframes slideUp {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        /* 添加卡片微妙的装饰效果 */
        .config-section::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 3px;
            background: linear-gradient(to right, var(--primary-color), var(--secondary-color));
            opacity: 0.5;
        }

        .form-control, .form-select {
            width: 100%;
            padding: 0.5rem 0.75rem;
            border-radius: 0.5rem;
            border: 1px solid var(--card-border) !important;
            background: var(--card-bg);
            color: var(--text-color);
            transition: all 0.3s ease;
        }

        .form-control:focus, .form-select:focus {
            border-color: var(--primary-color) !important;
            box-shadow: 0 0 0 0.25rem rgba(99, 102, 241, 0.25);
            outline: none;
        }

        .form-switch .form-check-input {
            width: 3em;
            height: 1.5em;
            margin-left: -3.5em;
        }

        .form-label {
            display: flex;
            align-items: center;
            margin-bottom: 0.5rem;
            font-weight: 500;
        }

        .badge-info {
            background: var(--primary-color);
            cursor: pointer;
        }

        .theme-switcher {
            position: fixed;
            bottom: 1rem;
            right: 1rem;
            z-index: 1000;
        }

        .accordion-button {
            background: transparent;
            border: none;
        }

        .accordion-button:not(.collapsed) {
            background: rgba(var(--bs-primary-rgb), 0.1);
            color: var(--primary-color);
        }

        .accordion-item {
            background: transparent;
            border-color: var(--card-border);
        }

        .toast {
            border-radius: 0.75rem;
            border: 1px solid rgba(255, 255, 255, 0.1);
        }
        .form-check-label {
            margin-top: 0;
        }

        /* 人设选择下拉栏样式 */
        select[name="AVATAR_DIR"] {
            max-height: 300px;
            overflow-y: auto;
        }


        .navbar .form-check.form-switch {
            display: flex;
            align-items: center;
            height: 100%;
            margin: 0;
        }


        .navbar .form-check-label {
            display: flex;
            align-items: center;
            margin: 0 0 0 8px;
            line-height: 1;
        }


        .navbar .form-check-input {
            margin: 0;
            vertical-align: middle;
        }

        /* 输入框组样式 */
        .input-group {
            border: 1px solid var(--card-border);
            border-radius: 0.5rem;
            overflow: hidden;
        }

        .input-group .form-control {
            border: none !important;
        }

        /* 配置项容器样式 */
        .config-item {
            margin-bottom: 1.5rem;
            padding: 1rem;
            border-radius: 0.5rem;
            background: rgba(255, 255, 255, 0.05);
            border: 1px solid rgba(255, 255, 255, 0.1);
        }

        /* 响应式布局 */
        @media (max-width: 700px) {
            .config-section {
                padding: 1rem;
            }
        }

        /* 密码输入框样式 */
        .password-input-group {
            position: relative;
        }

        .password-toggle {
            position: absolute;
            right: 10px;
            top: 50%;
            transform: translateY(-50%);
            background: none;
            border: none;
            cursor: pointer;
            color: var(--text-color);
            opacity: 0.7;
        }

        .password-toggle:hover {
            opacity: 1;
        }

        /* 修改左右两栏的间距 */
        @media (min-width: 768px) {
            .col-md-6.pe-md-2 {
                padding-right: 1.5rem !important;  /* 增加右边距 */
            }
            
            .col-md-6.ps-md-2 {
                padding-left: 1.5rem !important;   /* 增加左边距 */
            }
        }

        /* 修改响应式布局下的间距 */
        @media (max-width: 767px) {
            .col-md-6 {
                margin-bottom: 2rem;  /* 增加上下间距 */
            }
            
            .config-section {
                margin-bottom: 0;  /* 移除原有的底部间距 */
            }
            
            /* 为了让背景更好地显示，增加内容区域的内边距 */
            main.container-fluid {
                padding: 2rem 1rem;  /* 调整移动端的内边距 */
            }
            
            /* 为底部保存按钮留出空间 */
            main.container-fluid {
                padding-bottom: 5rem;  /* 底部留出更多空间 */
            }
        }

        /* 优化桌面端布局 */
        @media (min-width: 768px) {
            .col-md-6.pe-md-2 {
                padding-right: 1.5rem !important;
            }
            
            .col-md-6.ps-md-2 {
                padding-left: 1.5rem !important;
            }
            
            main.container-fluid {
                padding: 2rem;
                padding-bottom: 5rem;  /* 为底部保存按钮留出空间 */
            }
        }

        /* 修改主容器的内边距 */
        main.container-fluid {
            padding: 2rem;  /* 增加整体内边距 */
        }

        /* 添加相同的基础样式 */
        html, body {
            height: 100%;
            margin: 0;
            padding: 0;
        }

        body {
            display: flex;
            flex-direction: column;
            min-height: 100vh;
        }

        main {
            flex: 1 0 auto;
            width: 100%;
            padding: 2rem 0;
        }

        /* 添加通知动画 */
        .toast {
            transition: all 0.3s ease;
            transform: translateY(-20px);
            opacity: 0;
        }

        .toast.show {
            transform: translateY(0);
            opacity: 1;
        }

        /* 优化按钮悬停效果 */
        .btn-outline-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }

        /* 添加输入框过渡效果 */
        #customApiInput {
            transition: all 0.3s ease;
        }

        #customApiInput.show {
            transform: translateY(0);
            opacity: 1;
        }

        #customApiInput.hide {
            transform: translateY(-10px);
            opacity: 0;
        }

        /* 添加通知容器样式 */
        .notification-container {
            z-index: 1050;
        }

        .accordion-button {
            background: transparent !important;
        }
        
        .accordion-button:not(.collapsed) {
            color: rgb(147, 151, 255) !important;
        }
        
        .list-group-item {
            border: none;
            margin-bottom: 8px;
            border-radius: 8px !important;
            transition: all 0.3s ease;
        }
        
        /* 只针对定时任务的列表项应用深色样式 */
        #schedule-settings .list-group-item {
            background: rgba(30, 41, 59, 0.5);
            color: #fff;
        }
        
        #schedule-settings .list-group-item:hover {
            background: rgba(30, 41, 59, 0.8) !important;
            transform: translateX(5px);
        }
        
        /* 监听用户列表使用默认颜色 */
        #selected_users_LISTEN_LIST .list-group-item {
            background: var(--bs-list-group-bg);
            color: var(--bs-body-color);
        }
        
        /* 深色模式下的特定样式 */
        [data-bs-theme="dark"] #selected_users_LISTEN_LIST .list-group-item {
            background: rgba(30, 41, 59, 0.5);
            color: #fff;
        }
        
        /* 添加日期选择按钮组的响应式样式 */
        .btn-group.flex-wrap {
            display: flex;
            flex-wrap: wrap;
            gap: 0.25rem;
        }

        .btn-group.flex-wrap .btn {
            flex: 1 1 calc(14.28% - 0.25rem);
            min-width: 40px;
            padding: 0.375rem 0.5rem;
            font-size: 0.875rem;
            text-align: center;
        }

        /* 在小屏幕上调整按钮大小 */
        @media (max-width: 768px) {
            .btn-group.flex-wrap .btn {
                flex: 1 1 calc(33.33% - 0.25rem);
                min-width: 30px;
                padding: 0.25rem 0.375rem;
                font-size: 0.75rem;
            }
        }

        /* 在更小的屏幕上进一步调整 */
        @media (max-width: 480px) {
            .btn-group.flex-wrap .btn {
                flex: 1 1 calc(50% - 0.25rem);
                min-width: 25px;
                padding: 0.25rem;
                font-size: 0.75rem;
            }
        }
    </style>
    <script defer src="http://umami.kourichat.com/script.js" data-website-id="319cc5bc-c057-4f6c-8bc4-4af5e110add1"></script>
    <script src="/static/js/bootstrap.bundle.min.js"></script>
    <script src="/static/js/dark-mode.js"></script>
</head>
<body>
    {% include 'navbar.html' %}
    
    <main class="container-fluid py-4">
        <div class="row">
            <!-- 左侧基础配置 -->
            <div class="col-md-6 pe-md-2">
                <div class="config-section h-100">
                    <h4 class="mb-4">
                        <i class="bi bi-gear-fill me-2"></i>基础配置
                    </h4>
                    <form id="configForm">
                        {% for group_name, configs in config_groups.items() %}
                            {% if group_name == '基础配置' %}
                            <div class="accordion mb-3">
                                <div class="accordion-item">
                                    <h2 class="accordion-header">
                                        <button class="accordion-button" type="button" data-bs-toggle="collapse" 
                                            data-bs-target="#{{ group_name|replace(' ', '-') }}">
                                            {{ group_name }}
                                        </button>
                                    </h2>
                                    <div id="{{ group_name|replace(' ', '-') }}" class="accordion-collapse collapse show">
                                        <div class="accordion-body">
                                            {% for key, config in configs.items() %}
                                            <div class="mb-4">
                                                {% include 'config_item.html' %}
                                            </div>
                                            {% endfor %}
                                        </div>
                                    </div>
                                </div>
                            </div>
                            {% endif %}
                        {% endfor %}
                    </form>
                </div>
            </div>

            <!-- 右侧其他配置 -->
            <div class="col-md-6 ps-md-2">
                <div class="config-section h-100">
                    <h4 class="mb-4">
                        <i class="bi bi-sliders me-2"></i>高级配置
                    </h4>
                    <form id="otherConfigForm">
                        {% for group_name, configs in config_groups.items() %}
                            {% if group_name != '基础配置' and group_name != '定时任务配置' %}  {# 排除定时任务配置 #}
                            <div class="accordion mb-3">
                                <div class="accordion-item">
                                    <h2 class="accordion-header">
                                        <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" 
                                            data-bs-target="#{{ group_name|replace(' ', '-') }}">
                                            {{ group_name }}
                                        </button>
                                    </h2>
                                    <div id="{{ group_name|replace(' ', '-') }}" class="accordion-collapse collapse">
                                        <div class="accordion-body">
                                            {% for key, config in configs.items() %}
                                            <div class="mb-4">
                                                {% include 'config_item.html' %}
                                            </div>
                                            {% endfor %}
                                        </div>
                                    </div>
                                </div>
                            </div>
                            {% endif %}
                        {% endfor %}

                        <!-- 单独添加定时任务配置部分 -->
                        <div class="accordion mb-3">
                            <div class="accordion-item">
                                <h2 class="accordion-header">
                                    <button class="accordion-button collapsed" type="button" 
                                            data-bs-toggle="collapse" 
                                            data-bs-target="#schedule-settings"
                                            style="color: rgb(0, 0, 0); ">
                                        定时任务配置
                                    </button>
                                </h2>
                                <div id="schedule-settings" class="accordion-collapse collapse">
                                    <div class="accordion-body">
                                        <!-- 定时任务配置的内容 -->
                                        <input type="hidden" 
                                               id="TASKS" 
                                               name="TASKS" 
                                               value='{{ tasks_json|safe }}'>
                                        
                                        <!-- 添加和管理任务的按钮 -->
                                        <div class="mb-3 list-group">
                                            <a href="#" class="list-group-item list-group-item-action" 
                                               data-bs-toggle="modal" data-bs-target="#addTaskModal"
                                               style="background: rgba(30, 41, 59, 0.5);">
                                                <i class="bi bi-plus-lg me-2"></i>
                                                添加定时任务
                                                <i class="bi bi-chevron-right float-end mt-1"></i>
                                            </a>
                                        </div>
                                        
                                        <!-- 任务列表管理按钮 -->
                                        <div class="mb-3 list-group">
                                            <a href="#" class="list-group-item list-group-item-action" 
                                               data-bs-toggle="modal" data-bs-target="#taskListModal"
                                               style="background: rgba(30, 41, 59, 0.5);">
                                                <i class="bi bi-list-ul me-2"></i>
                                                任务列表管理
                                                <i class="bi bi-chevron-right float-end mt-1"></i>
                                            </a>
                                        </div>
                                        
                                        <!-- 说明文字 -->
                                        <div class="text-muted small">
                                            <i class="bi bi-info-circle me-1"></i>
                                            可以添加定时发送消息的任务，支持Cron表达式和时间间隔两种方式
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- 保存按钮固定在底部 -->
        <div class="position-fixed bottom-0 start-0 w-100 bg-body p-3 shadow-lg">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-12">
                        <button type="button" 
                            class="btn btn-primary btn-lg w-100" 
                            id="saveButton">
                            <i class="bi bi-save me-2"></i>保存所有设置
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <div class="toast-container">
        <div class="toast" role="alert" aria-live="assertive" aria-atomic="true">
            <div class="toast-body">
                <i class="bi bi-exclamation-triangle-fill text-danger"></i>
                <span class="toast-message"></span>
            </div>
        </div>
    </div>

    <!-- 在 body 标签下添加顶部通知区域 -->
    <div class="position-fixed top-0 start-50 translate-middle-x p-3 notification-container">
        <div id="saveNotification" class="toast align-items-center text-white bg-success border-0" role="alert" aria-live="assertive" aria-atomic="true">
            <div class="d-flex">
                <div class="toast-body">
                    <i class="bi bi-check-circle-fill me-2"></i>
                    <span id="saveNotificationMessage"></span>
                </div>
                <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="关闭通知"></button>
            </div>
        </div>
    </div>

    <!-- 监听用户列表为空的确认对话框 -->
    <div class="modal fade" id="emptyListenListModal" tabindex="-1" aria-labelledby="emptyListenListModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="emptyListenListModalLabel">
                        <i class="bi bi-exclamation-triangle-fill text-warning me-2"></i>提示
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
                </div>
                <div class="modal-body">
                    <p>您未填写监听用户，是否继续保存？</p>
                    <p class="text-muted small">未填写监听用户将导致机器人无法响应任何消息。</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" data-bs-dismiss="modal">否</button>
                    <button type="button" class="btn btn-secondary" id="confirmSaveBtn">是</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 任务列表模态框 -->
    <div class="modal fade" id="taskListModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="bi bi-list-check me-2"></i>定时任务列表
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
                </div>
                <div class="modal-body">
                    <div id="taskListContainer" class="list-group">
                        <!-- 默认显示无任务提示 -->
                        <div class="text-center text-muted p-4">
                            <i class="bi bi-inbox fs-2"></i>
                            <p class="mt-2">暂无定时任务</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加任务模态框 -->
    <div class="modal fade" id="addTaskModal" tabindex="-1" aria-labelledby="addTaskModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addTaskModalLabel">
                        <i class="bi bi-plus-circle me-2"></i>添加定时任务
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="taskForm">
                        <div class="row">
                            <!-- 左侧：基本信息 -->
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">
                                        <i class="bi bi-key me-2"></i>任务ID
                                    </label>
                                    <input type="text" class="form-control" id="taskId" required>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">
                                        <i class="bi bi-person me-2"></i>发送对象
                                    </label>
                                    <select class="form-select" id="taskChatId" required>
                                        <option value="">请选择发送对象</option>
                                    </select>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">
                                        <i class="bi bi-chat-text me-2"></i>消息内容
                                    </label>
                                    <textarea class="form-control" id="taskContent" rows="3" required></textarea>
                                </div>
                            </div>
                            
                            <!-- 右侧：定时设置 -->
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">
                                        <i class="bi bi-alarm me-2"></i>定时类型
                                    </label>
                                    <select class="form-select" id="scheduleType" onchange="toggleScheduleInput()">
                                        <option value="cron">Cron表达式</option>
                                        <option value="interval">时间间隔</option>
                                    </select>
                                </div>
                                
                                <!-- Cron表达式设置 -->
                                <div id="cronInputGroup" class="mb-3">
                                    <label class="form-label">
                                        <i class="bi bi-calendar3 me-2"></i>执行时间
                                    </label>
                                    <div class="row g-2">
                                        <div class="col-6">
                                            <select class="form-select" id="cronHour">
                                                <option value="*">每小时</option>
                                                <option value="0">0点</option>
                                                <option value="1">1点</option>
                                                <option value="2">2点</option>
                                                <option value="3">3点</option>
                                                <option value="4">4点</option>
                                                <option value="5">5点</option>
                                                <option value="6">6点</option>
                                                <option value="7">7点</option>
                                                <option value="8">8点</option>
                                                <option value="9">9点</option>
                                                <option value="10">10点</option>
                                                <option value="11">11点</option>
                                                <option value="12">12点</option>
                                                <option value="13">13点</option>
                                                <option value="14">14点</option>
                                                <option value="15">15点</option>
                                                <option value="16">16点</option>
                                                <option value="17">17点</option>
                                                <option value="18">18点</option>
                                                <option value="19">19点</option>
                                                <option value="20">20点</option>
                                                <option value="21">21点</option>
                                                <option value="22">22点</option>
                                                <option value="23">23点</option>
                                            </select>
                                        </div>
                                        <div class="col-6">
                                            <select class="form-select" id="cronMinute">
                                                <option value="0">整点</option>
                                                <option value="30">30分</option>
                                                <option value="15">15分</option>
                                                <option value="45">45分</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="mt-2">
                                        <label class="form-label">
                                            <i class="bi bi-calendar-week me-2"></i>执行周期
                                        </label>
                                        <div class="btn-group w-100 flex-wrap" role="group">
                                            <input type="checkbox" class="btn-check" id="cronWeekday1" autocomplete="off">
                                            <label class="btn btn-outline-primary flex-fill" for="cronWeekday1">一</label>
                                            
                                            <input type="checkbox" class="btn-check" id="cronWeekday2" autocomplete="off">
                                            <label class="btn btn-outline-primary flex-fill" for="cronWeekday2">二</label>
                                            
                                            <input type="checkbox" class="btn-check" id="cronWeekday3" autocomplete="off">
                                            <label class="btn btn-outline-primary flex-fill" for="cronWeekday3">三</label>
                                            
                                            <input type="checkbox" class="btn-check" id="cronWeekday4" autocomplete="off">
                                            <label class="btn btn-outline-primary flex-fill" for="cronWeekday4">四</label>
                                            
                                            <input type="checkbox" class="btn-check" id="cronWeekday5" autocomplete="off">
                                            <label class="btn btn-outline-primary flex-fill" for="cronWeekday5">五</label>
                                            
                                            <input type="checkbox" class="btn-check" id="cronWeekday6" autocomplete="off">
                                            <label class="btn btn-outline-primary flex-fill" for="cronWeekday6">六</label>
                                            
                                            <input type="checkbox" class="btn-check" id="cronWeekday7" autocomplete="off">
                                            <label class="btn btn-outline-primary flex-fill" for="cronWeekday7">日</label>
                                        </div>
                                    </div>
                                    <!-- 添加隐藏的cron表达式输入框 -->
                                    <input type="hidden" id="cronExpression" value="">
                                </div>
                                
                                <!-- 时间间隔设置 -->
                                <div id="intervalInputGroup" class="mb-3" style="display: none;">
                                    <label class="form-label">
                                        <i class="bi bi-hourglass-split me-2"></i>间隔时间
                                    </label>
                                    <div class="input-group">
                                        <input type="number" class="form-control" id="intervalValue" 
                                               min="1" step="1" placeholder="输入数值">
                                        <select class="form-select" id="intervalUnit" style="max-width: 120px;">
                                            <option value="60">分钟</option>
                                            <option value="3600">小时</option>
                                            <option value="86400">天</option>
                                        </select>
                                    </div>
                                    <div class="form-text">
                                        <i class="bi bi-info-circle me-1"></i>
                                        常用间隔：
                                        <div class="btn-group mt-1">
                                            <button type="button" class="btn btn-sm btn-outline-secondary" onclick="setInterval(30, '60')">30分钟</button>
                                            <button type="button" class="btn btn-sm btn-outline-secondary" onclick="setInterval(1, '3600')">1小时</button>
                                            <button type="button" class="btn btn-sm btn-outline-secondary" onclick="setInterval(2, '3600')">2小时</button>
                                            <button type="button" class="btn btn-sm btn-outline-secondary" onclick="setInterval(24, '3600')">1天</button>
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- 预览 -->
                                <div class="mt-3">
                                    <label class="form-label">
                                        <i class="bi bi-eye me-2"></i>执行时间预览
                                    </label>
                                    <div id="schedulePreview" class="form-control bg-light">
                                        请选择定时类型和设置
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="saveTask()">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 在页面中添加隐藏的配置数据 -->
    <script id="config_data" type="application/json">
        {{ config_json|safe }}
    </script>

    <script>
        // 护眼模式切换
        function toggleDarkMode() {
            document.body.setAttribute('data-bs-theme', 
                document.body.getAttribute('data-bs-theme') === 'dark' ? 'light' : 'dark');
        }

        // 初始化工具提示
        var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
        var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl)
        })

        // 页面加载时初始化所有配置数据
        document.addEventListener('DOMContentLoaded', function() {
            // 获取最新的配置数据
            fetch('/get_all_configs')
                .then(response => response.json())
                .then(data => {
                    if (data.status === 'success') {
                        // 更新所有配置项
                        updateAllConfigs(data.configs);
                        
                        // 更新任务列表
                        const tasksInput = document.getElementById('TASKS');
                        if (tasksInput && data.tasks) {
                            tasksInput.value = JSON.stringify(data.tasks);
                            updateTaskList();
                        }
                    } else {
                        console.error('获取配置数据失败:', data.message);
                    }
                })
                .catch(error => {
                    console.error('获取配置数据请求失败:', error);
                    // 如果请求失败，使用页面加载时的初始数据
                    const tasksInput = document.getElementById('TASKS');
                    if (tasksInput) {
                        updateTaskList();
                    }
                });
            
            // 获取保存按钮
            const saveButton = document.getElementById('saveButton');
            
            // 添加点击事件监听器
            saveButton.addEventListener('click', function() {
                const mainForm = document.getElementById('configForm');
                const otherForm = document.getElementById('otherConfigForm');
                const config = {};
                
                // 获取所有表单数据
                const formData = new FormData(mainForm);
                
                // 处理表单数据
                for (let [key, value] of formData.entries()) {
                    processFormValue(config, key, value);
                }
                
                if (otherForm) {
                    const otherFormData = new FormData(otherForm);
                    for (let [key, value] of otherFormData.entries()) {
                        processFormValue(config, key, value);
                    }
                }

                // 特别处理任务数据 - 确保直接从隐藏字段获取
                const tasksInput = document.getElementById('TASKS');
                if (tasksInput) {
                    try {
                        const tasksValue = tasksInput.value;
                        if (tasksValue) {
                            // 解析为JSON对象并添加到配置中
                            config['TASKS'] = JSON.parse(tasksValue);
                        }
                    } catch (e) {
                        // 出错时使用空数组
                        config['TASKS'] = [];
                    }
                }

                // 特别检查温度值
                const temperatureSlider = document.getElementById('TEMPERATURE_slider');
                const temperatureInput = document.getElementById('TEMPERATURE');
                if (temperatureSlider && temperatureInput) {
                    const tempValue = parseFloat(temperatureSlider.value);
                    if (!isNaN(tempValue)) {
                        config['TEMPERATURE'] = tempValue;
                    }
                }

                // 检查页面上是否有用户列表元素
                const userListElement = document.getElementById('selected_users_LISTEN_LIST');
                const hasUsers = userListElement && userListElement.querySelectorAll('.list-group-item').length > 0;
                
                // 根据是否有用户决定是否显示确认对话框
                if (!hasUsers) {
                    // 创建确认对话框
                    const confirmDialog = new bootstrap.Modal(document.getElementById('emptyListenListModal'));
                    confirmDialog.show();
                    
                    // 设置确认按钮的事件
                    document.getElementById('confirmSaveBtn').onclick = function() {
                        confirmDialog.hide();
                        saveConfig(config);
                    };
                } else {
                    // 直接保存配置
                    saveConfig(config);
                }
            });

            // 初始化背景
            fetch('/get_background')
                .then(response => response.json())
                .then(data => {
                    if (data.status === 'success' && data.path) {
                        document.body.style.backgroundImage = `url('${data.path}')`;
                    }
                })
                .catch(error => console.error('Error:', error));
        });

        // 更新所有配置项的函数
        function updateAllConfigs(configs) {
            // 遍历所有配置组和配置项
            for (const groupKey in configs) {
                const group = configs[groupKey];
                for (const configKey in group) {
                    const config = group[configKey];
                    const element = document.getElementById(configKey);
                    if (element) {
                        // 根据元素类型设置值
                        if (element.type === 'checkbox') {
                            element.checked = config.value;
                        } else if (element.tagName === 'SELECT') {
                            element.value = config.value;
                        } else {
                            element.value = config.value;
                        }
                        
                        // 特殊处理滑块
                        const slider = document.getElementById(`${configKey}_slider`);
                        if (slider) {
                            slider.value = config.value;
                            const display = document.getElementById(`${configKey}_display`);
                            if (display) {
                                display.textContent = typeof config.value === 'number' ? 
                                    (configKey === 'TEMPERATURE' ? config.value.toFixed(1) : config.value) : 
                                    config.value;
                            }
                        }
                        
                        // 特殊处理用户列表
                        if (configKey === 'LISTEN_LIST' && Array.isArray(config.value)) {
                            const userListElement = document.getElementById(`selected_users_${configKey}`);
                            if (userListElement) {
                                userListElement.innerHTML = '';
                                config.value.forEach(user => {
                                    if (user) {
                                        const userDiv = document.createElement('div');
                                        userDiv.className = 'list-group-item d-flex justify-content-between align-items-center';
                                        userDiv.innerHTML = `
                                            ${user}
                                            <button type="button" class="btn btn-danger btn-sm" onclick="removeUser('${configKey}', '${user}')">
                                                <i class="bi bi-x-lg"></i>
                                            </button>
                                        `;
                                        userListElement.appendChild(userDiv);
                                    }
                                });
                            }
                        }
                    }
                }
            }
        }

        // 保存配置的函数
        function saveConfig(config) {
            // 发送保存请求
            fetch('/save', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(config)
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    showSaveNotification(data.message);
                } else {
                    showSaveNotification(data.message, 'error');
                }
            })
            .catch(error => {
                showSaveNotification('保存失败：' + error, 'error');
            });
        }

        function processFormValue(config, key, value) {
            if (key === 'LISTEN_LIST') {
                config[key] = value.split(',').map(item => item.trim()).filter(item => item);
            } else if (key === 'TEMPERATURE') {
                // 特殊处理温度参数
                const tempValue = parseFloat(value);
                if (!isNaN(tempValue)) {
                    config[key] = tempValue;
                }
            } else if (key === 'TASKS') {
                try {
                    config[key] = JSON.parse(value);
                } catch (e) {
                    config[key] = [];
                }
            } else if (value.toLowerCase() === 'true' || value.toLowerCase() === 'false') {
                config[key] = value.toLowerCase() === 'true';
            } else if (!isNaN(value) && value !== '') {
                config[key] = Number(value);
            } else {
                config[key] = value;
            }
        }

        // 添加新函数
        function addToListFromSelect(key, value) {
            if (value === 'add_new') {
                document.getElementById('new_input_' + key).style.display = 'flex';
                setTimeout(() => {
                    document.querySelector(`select[onchange*="${key}"]`).value = '';
                }, 100);
                return;
            }
            
            if (value) {
                const targetElement = document.getElementById(key);
                const currentValues = targetElement.value ? targetElement.value.split(',') : [];
                if (!currentValues.includes(value)) {
                    currentValues.push(value);
                    targetElement.value = currentValues.join(',');
                    
                    // 添加到用户列表显示
                    const userListElement = document.getElementById('selected_users_' + key);
                    const userDiv = document.createElement('div');
                    userDiv.className = 'list-group-item d-flex justify-content-between align-items-center';
                    userDiv.innerHTML = `
                        ${value}
                        <button type="button" class="btn btn-danger btn-sm" onclick="removeUser('${key}', '${value}')">
                            <i class="bi bi-x-lg"></i>
                        </button>
                    `;
                    userListElement.appendChild(userDiv);
                }
            }
        }

        function addNewUser(key) {
            const inputElement = document.getElementById('input_' + key);
            const newValue = inputElement.value.trim();
            
            if (newValue) {
                const targetElement = document.getElementById(key);
                const currentValues = targetElement.value ? targetElement.value.split(',') : [];
                if (!currentValues.includes(newValue)) {
                    currentValues.push(newValue);
                    targetElement.value = currentValues.join(',');
                    
                    // 添加到用户列表显示
                    const userListElement = document.getElementById('selected_users_' + key);
                    const userDiv = document.createElement('div');
                    userDiv.className = 'list-group-item d-flex justify-content-between align-items-center';
                    userDiv.innerHTML = `
                        ${newValue}
                        <button type="button" class="btn btn-danger btn-sm" onclick="removeUser('${key}', '${newValue}')">
                            <i class="bi bi-x-lg"></i>
                        </button>
                    `;
                    userListElement.appendChild(userDiv);
                    
                    // 清空输入框
                    inputElement.value = '';
                }
            }
            updateTaskChatIdOptions();
        }

        function removeUser(key, userToRemove) {
            const targetElement = document.getElementById(key);
            const userListElement = document.getElementById('selected_users_' + key);
            
            // 更新隐藏的input值
            let currentValues = targetElement.value ? targetElement.value.split(',') : [];
            currentValues = currentValues.filter(user => user !== userToRemove);
            targetElement.value = currentValues.join(',');
            
            // 从显示列表中移除
            const userElements = userListElement.getElementsByClassName('list-group-item');
            for (let element of userElements) {
                if (element.textContent.trim() === userToRemove) {
                    element.remove();
                    break;
                }
            }
            updateTaskChatIdOptions();
        }

        // 添加背景图片上传处理
        document.getElementById('backgroundInput').addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                const formData = new FormData();
                formData.append('background', file);
                
                fetch('/upload_background', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.status === 'success') {
                        document.body.style.backgroundImage = `url('${data.path}')`;
                        showToast(data.message, 'success');
                    } else {
                        showToast(data.message, 'danger');
                    }
                })
                .catch(error => {
                    showToast('上传失败：' + error, 'danger');
                });
            }
        });

        function updateTemperature(key, value) {
            const displayElement = document.getElementById(key + '_display');
            if (displayElement) {
                displayElement.classList.add('updating');
                displayElement.textContent = parseFloat(value).toFixed(1);

                setTimeout(() => {
                    displayElement.classList.remove('updating');
                }, 300);
            }
        }

        function showSaveNotification(message, type = 'success') {
            const notification = document.getElementById('saveNotification');
            const messageElement = document.getElementById('saveNotificationMessage');
            
            // 移除现有的背景色类
            notification.classList.remove('bg-success', 'bg-danger');
            
            // 根据类型设置样式
            if (type === 'success') {
                notification.classList.add('bg-success');
            } else {
                notification.classList.add('bg-danger');
            }
            
            messageElement.textContent = message;
            
            const toast = new bootstrap.Toast(notification, {
                animation: true,
                autohide: true,
                delay: 3000
            });
            toast.show();
        }

        // 添加设置时间间隔的辅助函数
        function setInterval(value, unit) {
            document.getElementById('intervalValue').value = value;
            document.getElementById('intervalUnit').value = unit;
            updateSchedulePreview();
        }

        // 修改更新预览的函数
        function updateSchedulePreview() {
            const scheduleType = document.getElementById('scheduleType').value;
            const preview = document.getElementById('schedulePreview');
            
            if (scheduleType === 'cron') {
                const hour = document.getElementById('cronHour').value;
                const minute = document.getElementById('cronMinute').value;
                const weekdays = [];
                
                // 获取选中的星期
                for (let i = 1; i <= 7; i++) {
                    if (document.getElementById(`cronWeekday${i}`).checked) {
                        // 将1-7转换为0-6（0代表周日）
                        weekdays.push(i === 7 ? 0 : i - 1);
                    }
                }
                
                if (weekdays.length === 0) {
                    preview.textContent = '请选择执行周期';
                    return;
                }
                
                let previewText = `每天 ${hour === '*' ? '每小时' : hour + '点'} ${minute}分`;
                if (weekdays.length < 7) {
                    previewText = `每周 ${weekdays.map(w => ['日', '一', '二', '三', '四', '五', '六'][w]).join('、')} ${hour === '*' ? '每小时' : hour + '点'} ${minute}分`;
                }
                
                preview.textContent = previewText;
                
                // 更新cron表达式 - 修改为5字段格式
                const cronExp = `${minute} ${hour} * * ${weekdays.join(',')}`;
                document.getElementById('cronExpression').value = cronExp;
            } else {
                const value = document.getElementById('intervalValue').value;
                const unit = document.getElementById('intervalUnit').value;
                
                if (!value) {
                    preview.textContent = '请设置间隔时间';
                    return;
                }
                
                let unitText = '';
                switch(unit) {
                    case '60': unitText = '分钟'; break;
                    case '3600': unitText = '小时'; break;
                    case '86400': unitText = '天'; break;
                }
                
                preview.textContent = `每 ${value} ${unitText}`;
            }
        }

        // 修改格式化Cron表达式的函数
        function formatCronExpression(cronExp) {
            const [minute, hour, day, month, weekday] = cronExp.split(' ');
            let result = '';
            
            // 处理星期
            if (weekday !== '*') {
                const weekdays = weekday.split(',').map(w => ['日', '一', '二', '三', '四', '五', '六'][parseInt(w)]);
                result += `每周${weekdays.join('、')} `;
            } else {
                result += '每天 ';
            }
            
            // 处理时间
            if (hour === '*') {
                result += `每小时${minute}分`;
            } else {
                result += `${hour}点${minute}分`;
            }
            
            return result;
        }

        // 修改切换调度类型输入框的函数
        function toggleScheduleInput() {
            const scheduleType = document.getElementById('scheduleType').value;
            const cronInput = document.getElementById('cronInputGroup');
            const intervalInput = document.getElementById('intervalInputGroup');
            
            if (scheduleType === 'cron') {
                cronInput.style.display = 'block';
                intervalInput.style.display = 'none';
            } else {
                cronInput.style.display = 'none';
                intervalInput.style.display = 'block';
            }
            
            updateSchedulePreview();
        }

        // 为所有相关输入添加change事件监听
        document.addEventListener('DOMContentLoaded', function() {
            const inputs = [
                'cronHour', 'cronMinute',
                'cronWeekday1', 'cronWeekday2', 'cronWeekday3',
                'cronWeekday4', 'cronWeekday5', 'cronWeekday6', 'cronWeekday7',
                'intervalValue', 'intervalUnit'
            ];
            
            inputs.forEach(id => {
                const element = document.getElementById(id);
                if (element) {
                    element.addEventListener('change', updateSchedulePreview);
                }
            });
        });

        // 修改保存任务的函数
        function saveTask() {
            const taskId = document.getElementById('taskId').value.trim();
            const chatId = document.getElementById('taskChatId').value;
            const content = document.getElementById('taskContent').value.trim();
            const scheduleType = document.getElementById('scheduleType').value;
            
            // 验证必填字段
            if (!taskId || !chatId || !content) {
                showSaveNotification('请填写所有必填字段', 'error');
                return;
            }
            
            const task = {
                task_id: taskId,
                chat_id: chatId,
                content: content,
                schedule_type: scheduleType,
                is_active: true
            };
            
            // 根据调度类型设置相应的值
            if (scheduleType === 'cron') {
                const cronExp = document.getElementById('cronExpression').value;
                if (!cronExp) {
                    showSaveNotification('请设置执行时间', 'error');
                    return;
                }
                // 验证cron表达式格式
                const [minute, hour, day, month, weekday] = cronExp.split(' ');
                if (!/^\d+$/.test(minute) || !/^\d+$/.test(hour) || !/^[\d,]+$/.test(weekday)) {
                    showSaveNotification('Cron表达式格式不正确', 'error');
                    return;
                }
                task.schedule_time = cronExp;
            } else {
                const value = document.getElementById('intervalValue').value;
                const unit = document.getElementById('intervalUnit').value;
                
                if (!value) {
                    showSaveNotification('请设置间隔时间', 'error');
                    return;
                }
                
                // 计算总秒数
                const totalSeconds = parseInt(value) * parseInt(unit);
                task.schedule_time = totalSeconds.toString();
                task.interval = totalSeconds.toString();
            }
            
            // 获取现有的任务列表
            let tasks = [];
            try {
                const tasksInput = document.getElementById('TASKS');
                if (tasksInput && tasksInput.value) {
                    tasks = JSON.parse(tasksInput.value);
                }
            } catch (e) {
                console.error('解析任务列表失败:', e);
            }
            
            // 更新任务列表
            const existingIndex = tasks.findIndex(t => t.task_id === taskId);
            if (existingIndex >= 0) {
                tasks[existingIndex] = task;
            } else {
                tasks.push(task);
            }
            
            // 更新隐藏输入框的值
            document.getElementById('TASKS').value = JSON.stringify(tasks);
            
            // 关闭模态框
            const modal = bootstrap.Modal.getInstance(document.getElementById('addTaskModal'));
            modal.hide();
            
            // 显示成功提示
            showSaveNotification('任务已添加，请点击底部的"保存所有设置"按钮保存更改');
            
            // 刷新任务列表
            updateTaskList();
        }

        // 修改更新任务列表的函数
        function updateTaskList() {
            const container = document.getElementById('taskListContainer');
            if (!container) return;
            
            // 获取任务列表
            let tasks = [];
            try {
                const tasksInput = document.getElementById('TASKS');
                if (tasksInput && tasksInput.value) {
                    tasks = JSON.parse(tasksInput.value);
                }
            } catch (e) {
                console.error('解析任务列表失败:', e);
            }
            
            // 更新显示
            container.innerHTML = tasks.length === 0 ? `
                <div class="text-center text-muted p-4">
                    <i class="bi bi-inbox fs-2"></i>
                    <p class="mt-2">暂无定时任务</p>
                </div>
            ` : tasks.map(task => `
                <div class="list-group-item">
                    <div class="d-flex justify-content-between align-items-center">
                        <div class="me-auto">
                            <div class="d-flex align-items-center mb-1">
                                <span class="badge bg-primary me-2">${task.task_id}</span>
                                <span class="badge ${task.is_active ? 'bg-success' : 'bg-secondary'} me-2">
                                    ${task.is_active ? '运行中' : '已暂停'}
                                </span>
                            </div>
                            <div class="mb-1">
                                <i class="bi bi-person me-1"></i>发送给：${task.chat_id}
                            </div>
                            <div class="mb-1">
                                <i class="bi bi-clock me-1"></i>执行时间：
                                ${task.schedule_type === 'cron' ? 
                                    formatCronExpression(task.schedule_time) : 
                                    formatInterval(task.schedule_time)}
                            </div>
                            <div class="text-muted small">
                                <i class="bi bi-chat-text me-1"></i>${task.content}
                            </div>
                        </div>
                        <div class="btn-group">
                            <button class="btn btn-sm btn-outline-primary" onclick="toggleTask('${task.task_id}')" title="${task.is_active ? '暂停任务' : '启动任务'}">
                                <i class="bi bi-${task.is_active ? 'pause' : 'play'}-fill"></i>
                            </button>
                            <button class="btn btn-sm btn-outline-danger" onclick="deleteTask('${task.task_id}')" title="删除任务">
                                <i class="bi bi-trash"></i>
                            </button>
                        </div>
                    </div>
                </div>
            `).join('');
        }

        // 添加格式化时间间隔的函数
        function formatInterval(seconds) {
            const hours = parseInt(seconds) / 3600;
            if (hours >= 24) {
                return `每${hours/24}天`;
            } else if (hours >= 1) {
                return `每${hours}小时`;
            } else {
                return `每${hours*60}分钟`;
            }
        }

        // 添加切换任务状态的函数
        function toggleTask(taskId) {
            let tasks = [];
            try {
                const tasksInput = document.getElementById('TASKS');
                if (tasksInput && tasksInput.value) {
                    tasks = JSON.parse(tasksInput.value);
                }
            } catch (e) {
                return;
            }
            
            const taskIndex = tasks.findIndex(t => t.task_id === taskId);
            if (taskIndex >= 0) {
                tasks[taskIndex].is_active = !tasks[taskIndex].is_active;
                document.getElementById('TASKS').value = JSON.stringify(tasks);
                updateTaskList();
                showSaveNotification(`任务已${tasks[taskIndex].is_active ? '启动' : '暂停'}，请点击底部的"保存所有设置"按钮保存更改`);
            }
        }

        // 添加更新发送对象下拉框的函数
        function updateTaskChatIdOptions() {
            const chatSelect = document.getElementById('taskChatId');
            if (!chatSelect) return;
            
            // 保存当前选中的值
            const currentValue = chatSelect.value;
            
            // 清空现有选项
            chatSelect.innerHTML = '<option value="">请选择发送对象</option>';
            
            // 从监听列表获取用户
            const userElements = document.querySelectorAll('#selected_users_LISTEN_LIST .list-group-item');
            userElements.forEach(element => {
                const userName = element.textContent.trim().replace('×', '').trim();
                if (userName) {
                    chatSelect.innerHTML += `<option value="${userName}">${userName}</option>`;
                }
            });
            
            // 恢复之前选中的值
            if (currentValue) {
                chatSelect.value = currentValue;
            }
        }

        // 修改显示添加任务模态框时的处理
        document.getElementById('addTaskModal').addEventListener('show.bs.modal', function () {
            // 重置表单
            document.getElementById('taskForm').reset();
            
            // 更新发送对象下拉框
            updateTaskChatIdOptions();
            
            // 默认显示cron输入框
            toggleScheduleInput();
        });

        // 在用户列表变化时更新发送对象下拉框
        document.addEventListener('DOMContentLoaded', function() {
            // 监听用户列表的变化
            const userListElement = document.getElementById('selected_users_LISTEN_LIST');
            if (userListElement) {
                const observer = new MutationObserver(function(mutations) {
                    updateTaskChatIdOptions();
                });
                
                observer.observe(userListElement, {
                    childList: true,
                    subtree: true
                });
            }
            
            // 初始化时更新一次
            updateTaskChatIdOptions();
        });

        // 添加删除任务的函数
        function deleteTask(taskId) {
            if (confirm('确定要删除这个任务吗？')) {
                // 获取当前任务列表
                let tasks = [];
                try {
                    const tasksInput = document.getElementById('TASKS');
                    if (tasksInput && tasksInput.value) {
                        tasks = JSON.parse(tasksInput.value);
                    }
                } catch (e) {
                    return;
                }
                
                // 删除指定任务
                tasks = tasks.filter(t => t.task_id !== taskId);
                
                // 更新隐藏输入框的值
                document.getElementById('TASKS').value = JSON.stringify(tasks);
                
                // 刷新任务列表显示
                updateTaskList();
                
                showSaveNotification('任务已删除，请点击底部的"保存所有设置"按钮保存更改');
            }
        }

        // 添加页面关闭事件监听器
        window.addEventListener('beforeunload', function(e) {
            // 获取所有配置数据
            const mainForm = document.getElementById('configForm');
            const otherForm = document.getElementById('otherConfigForm');
            const config = {};
            
            // 获取所有表单数据
            const formData = new FormData(mainForm);
            
            // 处理表单数据
            for (let [key, value] of formData.entries()) {
                processFormValue(config, key, value);
            }
            
            if (otherForm) {
                const otherFormData = new FormData(otherForm);
                for (let [key, value] of otherFormData.entries()) {
                    processFormValue(config, key, value);
                }
            }

            // 特别处理任务数据
            const tasksInput = document.getElementById('TASKS');
            if (tasksInput) {
                try {
                    const tasksValue = tasksInput.value;
                    if (tasksValue) {
                        config['TASKS'] = JSON.parse(tasksValue);
                    }
                } catch (e) {
                    config['TASKS'] = [];
                }
            }

            // 特别检查温度值
            const temperatureSlider = document.getElementById('TEMPERATURE_slider');
            const temperatureInput = document.getElementById('TEMPERATURE');
            if (temperatureSlider && temperatureInput) {
                const tempValue = parseFloat(temperatureSlider.value);
                if (!isNaN(tempValue)) {
                    config['TEMPERATURE'] = tempValue;
                }
            }

            // 使用 navigator.sendBeacon 发送保存请求
            // 这种方式可以在页面关闭时可靠地发送数据
            const data = new FormData();
            data.append('config', JSON.stringify(config));
            
            // 发送保存请求
            navigator.sendBeacon('/save', data);
        });
    </script>
</body>
</html>
